package org.xqp.hrm.config;

import org.apache.lucene.search.Query;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import static org.xqp.hrm.constants.MQConstants.*;

//rabbitMQ的配置
@Configuration
public class RabbitMQConfig {

    //创建交换机
    @Bean
    public Exchange exchange(){
        return ExchangeBuilder.topicExchange(NAME_EXCHANGE_TOPIC).durable(true).build();
    }

    //创建短信队列
    @Bean
    public Queue smsQueue(){
        return  new Queue(NAME_QUEUE_SMS,true);
    }
    // 邮件队列
    @Bean
    public Queue emailQueue(){
        return  new Queue(NAME_QUEUE_EMAIL,true);
    }

    // 站内信队列
    @Bean
    public Queue messageQueue(){
        return  new Queue(NAME_QUEUE_MESSAGE,true);
    }

    // 绑定短信队列
    @Bean
    public Binding smsQueueBinding(){
        return BindingBuilder.bind(smsQueue()).to(exchange()).with("#.sms").noargs();
    }

    // 绑定邮件队列
    @Bean
    public Binding emailQueueBinding(){
        return BindingBuilder.bind(emailQueue()).to(exchange()).with("#.email").noargs();
    }

    // 绑定站内信队列
    @Bean
    public Binding messageQueueBinding(){
        return BindingBuilder.bind(messageQueue()).to(exchange()).with("#.message").noargs();
    }


    //定义RabbitTemplate 指定 JSON转换器
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
        //1.把要发送的消息内容 ，交换机，rontkey等都保存下来到Mysql
        //2.后续可以用来重写发送消息，甚至可以使用一个定时任务不停的重试，可以甚至一个最大重试次数
        //设置消息回调
        rabbitTemplate.setMandatory(true);
        return rabbitTemplate;
    }
}

